# Chat message model
from datetime import datetime
from datetime import datetime
from sqlalchemy import (
    Column, BigInteger, Integer, String, Text, DateTime, 
    Boolean, Enum, ForeignKey, JSON
)
from sqlalchemy.orm import relationship
from ..database import Base


class ChatMessage(Base):
    __tablename__ = "messages"
    
    id = Column(BigInteger, primary_key=True, index=True, comment="消息ID")
    session_id = Column(
        BigInteger, 
        ForeignKey("chat_sessions.id", ondelete="CASCADE"), 
        nullable=False, 
        comment="会话ID"
    )
    sender_type = Column(
        Enum("user", "avatar", name="sender_type_enum"), 
        nullable=False, 
        comment="发送者类型"
    )
    content = Column(Text, nullable=False, comment="消息内容")
    content_type = Column(
        Enum("text", "audio", "image", "mixed", name="content_type_enum"), 
        default="text", 
        comment="内容类型"
    )
    audio_url = Column(String(255), nullable=True, comment="音频文件URL")
    audio_duration = Column(Integer, nullable=True, comment="音频时长(秒)")
    emotion = Column(String(50), nullable=True, comment="情感标签")
    meta_data = Column("metadata", JSON, nullable=True, comment="元数据")
    parent_id = Column(
        BigInteger, 
        ForeignKey("messages.id", ondelete="SET NULL"), 
        nullable=True, 
        comment="回复的消息ID"
    )
    created_at = Column(
        DateTime, 
        default=datetime.utcnow, 
        nullable=False, 
        comment="创建时间"
    )
    is_deleted = Column(Boolean, default=False, comment="是否已删除")
    
    # 关系
    session = relationship("ChatSession", back_populates="messages")
    parent = relationship(
        "ChatMessage", 
        remote_side=[id], 
        back_populates="replies"
    )
    replies = relationship(
        "ChatMessage", 
        back_populates="parent", 
        overlaps="parent"
    )


# 向后兼容的别名
MessageType = object 